package main;

import java.util.Enumeration;
import java.util.concurrent.RejectedExecutionException;

import utils.ThreadPool;
import action.WebSourceCollector;

public class RequestManager extends Thread {
    public ThreadPool executor;

    private static RequestManager singleton;
    
    public boolean finishOnEveryThreadDone = false;
    
    public static RequestManager instance() {
        if (singleton == null) {
            singleton = new RequestManager();
        }
        return singleton;
    }

    public static void init() {
        if (singleton == null) {
            singleton = new RequestManager();
        }
        singleton.executor = new ThreadPool(Global.REQUEST_MANAGER_CORE_POLL_SIZE, Global.REQUEST_MANAGER_MAX_POLL_SIZE);
        singleton.executor.start();
        singleton.start();
    }

    private RequestManager() {
    }

    @Override
    public void run() {
        while (true) {
            Enumeration<Thread> keys = executor.threads.keys();
            while (keys.hasMoreElements()) {
                Thread thread = keys.nextElement();
                WebSourceCollector collector = (WebSourceCollector) executor.threads.get(thread).toRun;
                if (collector != null) {
                    if (System.currentTimeMillis() - collector.startTime > Global.MAX_TIME_RUN_DURATION_EACH_THREAD) {
                        String url = collector.url;
                        collector.close();
                        executor.removeThread(thread);
                        System.out.println("Killed thread by timeout " + "[" + executor.threads.size() + "]: " + url);
                    }
                } else {
                    executor.removeThread(thread);
                }
            }
            
            if (finishOnEveryThreadDone && executor.threads.values().size() == 0) {
                break;
            }
            
            try {
                sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    
    public void addRequest(WebSourceCollector collector) {
        try {
            executor.runIt(collector);
        } catch (RejectedExecutionException ex) {
            System.out.println("Rejected request from [" + collector.url + "]");
        }
    }
}